package com.night.card.exception;


import cn.hutool.core.exceptions.ValidateException;
import com.night.common.entity.ResultVo;
import com.night.common.entity.StatusCode;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.nio.file.AccessDeniedException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author CHX42
 * @Description 统一异常处理
 * @Date  2022/10/27  9:39
 * @Param 
 * @return 
 **/
@RestControllerAdvice(basePackages = "com.night.card.controller")
public class GlobalAdvisor {
    @ExceptionHandler
    public ResultVo<String> exceptionHandler(Exception e) {
        e.printStackTrace();
        return new ResultVo<>(StatusCode.ERROR);
    }
    //用于前端数据传输校验异常捕获
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVo<Map<String, String>> handlerMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        Map<String, String> map = new HashMap<>();
        exception.getBindingResult().getFieldErrors().forEach(e -> map.put(e.getField(), e.getDefaultMessage()));
        return new ResultVo<>(StatusCode.VALUE_FAIL.code, StatusCode.VALUE_FAIL.msg, map);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResultVo<Map<String, String>> handlerConstraintViolationException(ConstraintViolationException exception) {
        Map<String, String> map = new HashMap<>();
        exception.getConstraintViolations().forEach(e -> map.put(e.getPropertyPath().toString(), e.getMessage()));
        return new ResultVo<>(StatusCode.VALUE_FAIL.code, StatusCode.VALUE_FAIL.msg, map);
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ResultVo<?> handlerAccessDeniedException(AccessDeniedException exception) {
        return new ResultVo<>(StatusCode.NO_PERM);
    }

    @ExceptionHandler(ValidateException.class)
    public ResultVo<?> handlerValidateException(ValidateException exception) {
        return new ResultVo<>(StatusCode.CAPTCHA_FAIL);
    }

}
